import { GameConfigData } from "./GameConfig";
import {MD5} from "./Md5_0"
// export let HTTPURL = "https://open.chaotin.net/api/dyqlb/"//服务器
export let HTTPURL = "http://192.168.3.57:8090/api/dyqlb/"//本地
export let HttpMrg: HttpService;
export class HttpService {
    private static _inst: HttpService;

    private constructor() {
    }

    //初始化
    static getInst(): HttpService {
        if (!this._inst) {
            this._inst = new HttpService();
            //@ts-ignore
            HttpMrg = this._inst;
        }
        
        undefined
        return this._inst;
    }

    /**
    * 
    * @param url 地址
    * @param headers 
    * @param params 参数
    * @param cb //回调
    */
    //get请求
    httpRequestByGet(url: string, params, cb) {
        if (params) {
            if (url.indexOf("?") == -1) {
                url += "?";
            }
            url += this.getQueryString(params);
        }
        this.doHttp(url, null, "GET", cb);
    }

    /**
    * 
    * @param url 地址
    * @param params 参数
    * @param cb //回调
    */
    //post请求
    httpRequestByPost(url: string, params, cb) {
        let data = null;
        if (url.indexOf("post_view_ad_log") == -1) {
            data = this.sortDataAndMD5(params, url);
        }
        else data = params

        this.doHttp(url, data, "POST", cb);
    }

    /**
     * 
     * @param url 地址
     * @param headers 
     * @param params 参数
     * @param method 请求方式
     * @param cb //回调
     */
    private doHttp(url: string, params, method: string, cb) {
        const xhr = new XMLHttpRequest();
        xhr.responseType = "text";
        xhr.timeout = 6000;
        xhr.onreadystatechange = this.onReadyStateChange.bind(this, xhr, cb);
        xhr.ontimeout = this.onTimeout.bind(this, xhr, HTTPURL + url);
        xhr.onerror = this.onError.bind(this, xhr, HTTPURL + url);
        xhr.onabort = this.onAbort.bind(this, xhr, HTTPURL + url);

        console.log("url=====================>", HTTPURL + url);
        xhr.open(method, HTTPURL + url, true);
        //设置请求头
        this.setHttpHeaders(xhr, { "token": GameConfigData.token });
        this.setHttpHeaders(xhr, { "Content-Type": "application/x-www-form-urlencoded" });

        let obj = null;
        if (params && typeof params === "object") {
            for (const key in params) {
                if (obj) {
                    obj += "&" + key + `=${params[key]}`;
                } else {
                    obj = key + `=${params[key]}`;
                }
            }
        }
        xhr.send(obj);
    }

    private sortDataAndMD5(data, type) {
        let val = "";
        for (let key in data) {
            if (key != "sign") val += data[key]
        }
        let md5Key = GameConfigData.md5_key != "" ? GameConfigData.md5_key : "sdfji23u89sdhf3ji32ji2";
        data.sign = MD5.md5(val + md5Key + GameConfigData.token);
        return data;
    }

    private onReadyStateChange(xhr: XMLHttpRequest, cb) {
        cc.log(`HttpService, onReadyStateChange, readyState=${xhr.readyState}, status=${xhr.status}`);
        if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
            cc.log(`HttpService, onReadyStateChange, responseText=${xhr.responseText}`);
            let data;
            let code = HttpCode.kUnknown;
            const response = JSON.parse(xhr.responseText);
            if (response && response.code) {
                code = response.code;
                data = response.content;
            }
            else {
                code = HttpCode.kSuccess;
                data = response;
            }
            this.notifyCallback(cb, code, data);
            this.removeXhrEvent(xhr);
        }
    }

    private onTimeout(xhr: XMLHttpRequest, url: string) {
        cc.warn(`${url}, request ontimeout`);
        this.removeXhrEvent(xhr);
    }

    private onError(xhr: XMLHttpRequest, url: string) {
        cc.warn(`${url}, request onerror`);
        this.removeXhrEvent(xhr);
    }

    private onAbort(xhr: XMLHttpRequest, url: string) {
        cc.warn(`${url}, request onabort`);
        this.removeXhrEvent(xhr);
    }

    private removeXhrEvent(xhr: XMLHttpRequest) {
        xhr.ontimeout = null;
        xhr.onerror = null;
        xhr.onabort = null;
        xhr.onreadystatechange = null;
    }

    private notifyCallback(cb, code: number, data?) {
        if (cb) {
            cb(code, data);
        }
    }

    private setHttpHeaders(xhr: XMLHttpRequest, headers) {
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key]);
        }
    }

    private getQueryString(params) {
        const tmps: string[] = [];
        for (let key in params) {
            tmps.push(`${key}=${params[key]}`);
        }
        let url = tmps.join("&");
        return url
    }
}

export enum HttpCode {
    kSuccess = 0,
    kTimeout = 3000,
    kUnknown = 10001,
    kSessionTimeout = -8,
    kIAmInBlocklist = -3013,
    kUserIsInMyBlocklist = -3014
}